<template>
  <div class="anchor">
    <search-table
      :url="url"
      ref="searchtable"
      :columns="columns"
      :headParams="headParams"
      :defaultParams="userInfo.shopRoleCode == 'role:store:main' ? {} : defaultParams"
      :form="form">
      <!-- 搜索条件 -->
      <template slot="searchForm">
        <a-form layout="inline" :form="form">
          <a-form-item v-if="userInfo.shopRoleCode == 'role:store:main'" label="直播平台">
            <a-select
              showSearch
              allowClear
              style="width: 195px"
              :options="liveAppIdList"
              v-decorator="[
                'appId',
                {
                  initialValue: userInfo.shopRoleCode == 'role:store:main' ? '100000054' : (userInfo.shopRoleCode == 'role:store:branch' ? '100000055' : '')
                }
              ]"
              placeholder="请选择"
              @change="appIdChange">
            </a-select>
          </a-form-item>
          <a-form-item v-if="userInfo.shopRoleCode == 'role:store:main'" label="所属店铺">
            <a-select
              showSearch
              allowClear
              style="width: 195px"
              v-decorator="[
                'blongShop',
                {
                  initialValue: 1
                }
              ]"
              placeholder="请选择所属店铺"
              @change="blongShopChange">
              <a-select-option :value="1">本店直播</a-select-option>
              <a-select-option v-if="activeAppId == '100000055'" :value="2">其它店直播</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="主播昵称">
            <a-input style="width: 195px" allowClear v-decorator="['anchorName']" placeholder="请输入主播昵称"></a-input>
          </a-form-item>
          <a-form-item label="主播微信号">
            <a-input style="width: 195px" allowClear v-decorator="['anchorWechat']" placeholder="请输入主播微信号"></a-input>
          </a-form-item>
          <a-form-item label="主播状态">
            <a-select
              showSearch
              allowClear
              style="width: 195px"
              :options="statusList"
              v-decorator="['status']"
              placeholder="请选择">
            </a-select>
          </a-form-item>
          <a-form-item label="添加时间">
            <fast-range-picker
              v-decorator="[ 'createTime-updateTime' ]"
            />
            <!-- <a-date-picker
              allow-clear
              v-decorator="['creatTime']"
              format="YYYY-MM-DD HH:mm:ss" /> -->
          </a-form-item>
        </a-form>
      </template>
      <!-- 操作栏 -->
      <template slot="oprationRow">
        <permission authority="user:add">
          <a-button type="primary" icon="plus" @click="openInfo({}, 'add')">添加新主播</a-button>
        </permission>
        <permission authority="user:delete">
          <a-button type="danger" @click="deleteAnchor($refs.searchtable.selectedRowKeys)">删除</a-button>
        </permission>
      </template>
      <!-- 表格行操作 -->
      <template slot="tableOperation" slot-scope="{ record }">
        <a-space>
          <permission v-if="activeBlongShop == 1 && record.status == 0" authority="user:certification">
            <span class="text-danger pointer" @click="certificationFun(record)">实名认证</span>
          </permission>
          <permission v-if="activeBlongShop == 1 && record.status != 2" authority="user:update">
            <span class="text-primary pointer" @click="openInfo(record, 'edit')">编辑</span>
          </permission>
          <permission v-if="record.status == 1" authority="user:updateStatus">
            <span class="text-primary pointer" @click="setAnchorStatus(record, '2')">禁用</span>
          </permission>
          <permission v-if="record.status == 2" authority="user:updateStatus">
            <span class="text-primary pointer" @click="setAnchorStatus(record, '1')">解除禁用</span>
          </permission>
          <permission authority="user:delete">
            <span class="text-danger pointer" @click="deleteAnchor([record.id])">删除</span>
          </permission>
        </a-space>
      </template>
    </search-table>
    <!-- 主播信息弹窗 -->
    <anchor-form ref="anchorForm" :handle="handle" :record="currentRecord" :appId="userInfo.shopRoleCode == 'role:store:main' ? activeAppId : (userInfo.shopRoleCode == 'role:store:branch' ? defaultParams.appId : '')" :visible="infoVisible" @cancel="closeModal"></anchor-form>
    <!-- 实名认证弹窗 -->
    <a-modal
      :visible="certifiedVisible"
      :title="'扫码实名认证'"
      :destroyOnClose="true"
      :confirmLoading="certifiedConfirmLoading"
      width="500px"
      @cancel="closeModal(false)"
      @ok="certificationSubmit">
      <div class="certified-img">
        <img src="https://res.wx.qq.com/op_res/9rSix1dhHfK4rR049JL0PHJ7TpOvkuZ3mE0z7Ou_Etvjf-w1J_jVX0rZqeStLfwh" alt="">
      </div>
    </a-modal>
  </div>
</template>

<script>
  import { mapGetters } from "vuex";
  import { findDictNameByValue,createOptionsByDict } from '@/utils/dict'
  import anchorForm from './components/anchorForm.vue';
  export default {
    name: "MarketingAnchor",
    components: {
      anchorForm
    },
    data() {
      return {
        url: '/user/page', // 列表接口地址
        form: this.$form.createForm(this, {
          name: "table_search",
          mapPropsToFields: () => {
            let appId='',blongShop=1
            if(this.$route.query.appId){
              appId = this.$route.query.appId
            } else {
              if(this.$store.state.userInfo.shopRoleCode == 'role:store:main') {
                appId=createOptionsByDict('LIVE_APPID')[0] ? createOptionsByDict('LIVE_APPID')[0].value : '100000054'
              } else if(this.$store.state.userInfo.shopRoleCode == 'role:store:branch') {
                appId=createOptionsByDict('LIVE_APPID')[1] ? createOptionsByDict('LIVE_APPID')[1].value : '100000055'
              }
            }
            if(this.$route.query.blong) {
              blongShop = Number(this.$route.query.blong)
            } else {
              blongShop = 1
            }
            return {
              appId: this.$form.createFormField({
                ...appId,
                value: appId,
              }),
              blongShop: this.$form.createFormField({
                ...blongShop,
                value: blongShop,
              })
            }
          }
        }), // 搜索条件表单
        activeAppId: this.$route.query.appId || '100000054', // 当前直播平台，默认100000054
        activeBlongShop: 1, // 当前所属店铺，默认为本店
        headParams: { baseURL: '/goldenhome/gh/live/admin' }, // 列表接口域名
        defaultParams: {
          appId: this.$store.state.userInfo.shopRoleCode == 'role:store:branch' ? '100000055' : '',
          blongShop: this.$store.state.userInfo.shopRoleCode == 'role:store:branch' ? 1 : null
        }, // 列表默认携带参数
        liveAppIdList: createOptionsByDict('LIVE_APPID'), // 直播平台
        statusList: createOptionsByDict('LIVE_ANCHOR_STATUS'), // 主播状态
        handle: '', // 操作类型
        currentRecord: {}, // 选中行数据
        infoVisible: false, // 是否显示弹窗
        certifiedVisible: false, // 是否显示实名认证弹窗
        certifiedConfirmLoading: false, // 实名认证弹窗按钮提交状态
        columns: [
          {
            title: "主播昵称",
            dataIndex: "anchorName",
            width: 125,
            key: "anchorName",
          },
          {
            title: "主播微信号",
            dataIndex: "anchorWechat",
            width: 125,
            key: "anchorWechat"
          },
          {
            title: "主播头像",
            dataIndex: "headPicture",
            width: 125,
            key: "headPicture",
            customRender: (text, record) => {
              return <table-img src={text}/>
            }
          },
          {
            title: "添加时间",
            dataIndex: "createTime",
            width: 125,
            key: "createTime"
          },
          {
            title: "所属平台",
            dataIndex: "appName",
            width: 125,
            key: "appName"
          },
          {
            title: "所属机构",
            dataIndex: "orgName",
            width: 125,
            key: "orgName"
          },
          {
            title: "所属店铺",
            dataIndex: "shopName",
            width: 125,
            key: "shopName"
          },
          {
            title: "状态",
            dataIndex: "status",
            width: 125,
            key: "status",
            customRender: (text, record) => findDictNameByValue('LIVE_ANCHOR_STATUS', text)
          },
          {
            title: "操作",
            dataIndex: "operation",
            width: 125,
            scopedSlots: { customRender: "operation" },
          }
        ],
      }
    },
    watch: {},
    computed: {
      ...mapGetters(["userInfo"]),
    },
    created() {},
    mounted() {},
    methods: {
      // 切换直播平台
      appIdChange(val) {
        this.activeAppId = val
        if(val == '100000054') {
          this.form.setFieldsValue({
            blongShop: 1,
          });
        }
      },
      // 切换所属店铺
      blongShopChange(val) {
        this.activeBlongShop = val
      },
      // 实名认证
      certificationFun(record) {
        this.currentRecord = record
        this.certifiedVisible = true
      },
      // 验证主播是否实名认证
      certificationSubmit() {
        this.certifiedConfirmLoading = true
        this.$post('/user/updateAuthStatus',
            this.currentRecord,
            { baseURL: `${location.origin}/goldenhome/gh/live/admin` })
        .then((res) => {
          if (res && res.returnCode == 1000) {
            this.certifiedConfirmLoading = false
            this.certifiedVisible = false
            this.$refs.searchtable.refreshTable();
          }
        })
        .catch(err=> {
          this.certifiedConfirmLoading = false
        })
      },
      // 添加主播
      openInfo(record, type) {
        this.currentRecord = record
        this.handle = type
        this.infoVisible = true
      },
      // 关闭弹窗
      closeModal(freshTable) {
        this.certifiedVisible = false
        this.infoVisible = false
        if (freshTable) {
          this.$refs.searchtable.refreshTable();
        }
      },
      // 禁用  解除禁用
      setAnchorStatus(record, status) {
        let params = {}
        params.id = record.id
        params.status = status
        this.$post('/user/updateStatus',
            params,
            { baseURL: `${location.origin}/goldenhome/gh/live/admin` }).then((res) => {
          if (res && res.returnCode == 1000) {
            this.$refs.searchtable.refreshTable();
          }
        });
      },
      // 删除主播
      deleteAnchor(ids) {
        if(ids.length == 0) {
          this.$message.warning('请先选择一项后再进行操作！');
          return
        }
        let _this = this;
        this.$confirm({
          title: '删除操作',
          content: '是否确定删除该主播，删除后将不可恢复！',
          okText: '确认删除',
          cancelText: '取消',
          onOk() {
            _this.$post('/user/delete',
                { ids: ids },
                { baseURL: `${location.origin}/goldenhome/gh/live/admin` }).then((res) => {
              if (res && res.returnCode == 1000) {
                _this.$message.success('删除成功');
                _this.$refs.searchtable.refreshTable();
              }
            });
          },
          onCancel() {},
        });
      },
    }
  }
</script>

<style scoped lang="less">
  // .anchor{ }
  .certified-img{
    width: 400px;
    height: 400px;
    margin: 0 auto;
    img{
      width: 100%;
    }
  }
</style>
